/* 
 支付
 */

/* 
 页面内使用
 import { usePay } from '@/hooks/usePay.js'
 const { weixinH5Pay, appPay } = usePay()
 
 // 微信H5调起微信支付
 // wxJsApiParam 微信支付验证参数(后台接口调用微信商家支付平台回调)
// 微信H5支付
try {
    await weixinH5Pay(wxJsApiParam)
    console.log('支付成功')
} catch (error) {
    console.error('支付失败:', error)
}
 
 // APP、小程序支付
 // orderInfo 订单数据
 // provider  服务供应商
try {
    await appPay(orderInfo, 'wxpay')
    console.log('支付成功')
} catch (error) {
    console.error('支付失败:', error)
}
 */

/**
 * 支付Hook
 * 提供微信H5支付和APP/小程序支付功能
 */
const usePay = () => {
    /**
     * 微信H5支付
     * @param {Object} wxJsApiParam 微信支付参数
     * @returns {Promise} 返回支付结果
     */
    const weixinH5Pay = (wxJsApiParam) => {
        return new Promise((resolve, reject) => {
            const jsApiCall = (jsPara) => {
                if (typeof WeixinJSBridge === 'undefined') {
                    reject(new Error('微信支付环境未准备好'))
                    return
                }

                WeixinJSBridge.invoke('getBrandWCPayRequest', {
                    "appId": jsPara.appId,
                    "nonceStr": jsPara.nonceStr,
                    "package": jsPara.package,
                    "paySign": jsPara.paySign,
                    "signType": jsPara.signType,
                    "timeStamp": jsPara.timeStamp
                }, (res) => {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                        resolve('支付成功')
                    } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
                        reject(new Error('用户取消支付'))
                    } else {
                        reject(new Error('支付失败'))
                    }
                })
            }

            if (typeof WeixinJSBridge !== "undefined") {
                jsApiCall(wxJsApiParam)
            } else {
                const readyHandler = () => {
                    document.removeEventListener('WeixinJSBridgeReady', readyHandler)
                    jsApiCall(wxJsApiParam)
                }
                document.addEventListener('WeixinJSBridgeReady', readyHandler)
            }
        })
    }

    /**
     * APP/小程序支付
     * @param {Object|String} orderInfo 订单信息
     * @param {String} [provider] 支付提供商
     * @returns {Promise} 返回支付结果
     */
    const appPay = (orderInfo, provider) => {
        return new Promise((resolve, reject) => {
            uni.getProvider({
                service: "payment",
                success: (res) => {
                    const providerInfo = provider || res.provider[0]
                    let order = orderInfo

                    // 处理支付宝参数格式
                    if (providerInfo === 'alipay' && typeof orderInfo === 'object') {
                        order = JSON.stringify(orderInfo)
                    } else if (providerInfo !== 'alipay' && typeof orderInfo === 'string') {
                        order = JSON.parse(orderInfo)
                    }

                    uni.requestPayment({
                        provider: providerInfo,
                        orderInfo: order,
                        success: resolve,
                        fail: (err) => {
                            reject(err.errMsg || '支付失败')
                        }
                    })
                },
                fail: () => {
                    reject('获取支付服务商失败')
                }
            })
        })
    }

    return { weixinH5Pay, appPay }
}

export { usePay }